package aos;

//author : Rakesh Sugirtharaj
import java.io.*;
import java.net.*;

public class Server {

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		// create a new server socket
		try {
			serverSocket = new ServerSocket(5060);
		} catch (IOException e) {
			System.out.println("ERROR : Cannot open socket at port 5060");
			e.printStackTrace();
		}
		while (true) {
			try {
				final Socket client = serverSocket.accept();

				Runnable job = new Runnable() {
					public void run() {
						try {
							PrintWriter writer = new PrintWriter(
									client.getOutputStream(), true);
							BufferedReader bufRead = new BufferedReader(
									new InputStreamReader(
											client.getInputStream()));
							String line;
							while ((line = bufRead.readLine()) != null) {
								String[] temp = line.split(":");
								int reqType = Integer.parseInt(temp[1]);
								String reply = null;
								switch (reqType) {
								case 1: // enquiry
									File rootDir = new File("documents");
									for (String fileName : rootDir.list()) {
										if (reply == null) {
											reply = fileName;
										} else {
											reply = reply + "," + fileName;
										}
									}
									writer.println(reply);
									break;
								case 2: // read
									File readFile = new File("documents/"
											+ temp[2]);
									BufferedReader br = new BufferedReader(
											new InputStreamReader(
													new FileInputStream(
															readFile)));
									String lastLine = null;
									String temp1 = null;
									while ((temp1 = br.readLine()) != null) {
										lastLine = temp1;
									}
									writer.println(lastLine);
									br.close();
									break;
								case 3: // write
									File writeFile = new File("documents/" + temp[2]);
									FileWriter fw = new FileWriter(writeFile,true);
									fw.write("\n" + temp[3]);
									
									writer.println("END-OF-MESSAGE");
									fw.close();
									break;
								default://error
									writer.println("ERROR");
								}
							}
							writer.close();
							bufRead.close();
							client.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};
				Thread clientThread = new Thread(job);
				clientThread.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
